package com.uzai.console.common.web.interceptor;

import com.uzai.console.common.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author mingyang.chen create in 2022/8/24 09:55
 */
@Slf4j
public class TraceIdInterceptor implements HandlerInterceptor {

    public static final String TRACE_ID = "TraceId";
    public static final String TRACE_URI = "TraceUrl";
    public static final String UNKNOWN = "UNKNOWN";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MDC.put(TRACE_URI, StringUtils.defaultIfBlank(request.getRequestURI(), UNKNOWN));
        MDC.put(TRACE_ID, StringUtils.defaultIfBlank(request.getHeader(TRACE_ID), CommonUtil.getUUID().toUpperCase()));
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.clear();
    }
}
